<?php
defined('_JEXEC') or die;
jimport('joomla.application.component.controller');
jimport('joomla.filesystem.file');
class VolunteerController extends JController
{
	var $errorMessageAdminPermissionRequired = 'Please login as an Administrator to access this page';
	var $errorMessageModelError = 'There has been an error. Please try again.';
	
	function display()
	{
		// must login to access this component
		if ($this->authenticate() == false)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_normal&view=login'));
			return false;
		}	
		
		$viewName = JRequest::getVar('view');
		if (!$viewName)
			$viewName = 'volunteer'; //default view;
		
		if ($this->isAdmin() == false) //is a volunteer
		{
			if ($viewName == 'addfile' || $viewName == 'searchfile' || $viewName == 'uploadedfiles' || $viewName == 'updatepassword' || $viewName == 'editfile' || $viewName == 'volunteer' || $viewName == 'filedetail' || $viewName == 'help') //viewable by both admin and volunteer
			{
				// do nothing
			}
			else //viewable by admin only
			{
				$this->logout();
				$this->setRedirect(JRoute::_('index.php?option=com_normal&view=login'), 'Please login as an Administrator to access this page', 'error');
				return false;
			}
		}
		
		$model = $this->getModel('volunteer');
		$app = JFactory::getApplication();
		$app->setTemplate("gippslandsitetemplate3"); 
		
		if($viewName == "filedetail" || $viewName == "editfile")
		{
			$id = JRequest::getVar('fileid');
			
			// $app = JFactory::getApplication();
			$data = $app->getUserState('volunteer.' . $viewName . '.form.data');
			if(!$data) $data = array();
			
			$path = JURI::base() . 'components/com_volunteer/Audio/';
			$data['linkToFile'] = $path . $model->getFile($id)->url;
			
			$app->setUserState('volunteer.' . $viewName . '.form.data', $data);
		}
		
		$view =& $this->getView($viewName, 'html');
		$view->setModel($model);
		$view->display();
	}
	
	function authenticate()
	{
		$session =& JFactory::getSession();
		$username = $session->get('username');
		
		if ($username)
			return true;
		else
			return false;
	}
	
	function isAdmin()
	{
		$session =& JFactory::getSession();
		$is_admin = $session->get('is_admin');
		
		return $is_admin == 'y' && $this->authenticate();
	}
	
	function login()
	{
		$model         = $this->getModel('volunteer');
		$volunteername = JRequest::getVar('username');
		$volunteerpwd  = JRequest::getVar('password');
		
		$userobj = $model->authenticate($volunteername, $volunteerpwd);
		
		if ($userobj->user_id == '') //unexist user
		{
			$this->setRedirect(JRoute::_('index.php?option=com_normal&view=login'), JText::sprintf('Wrong username or password'), 'error');
			return false;
		}
		else
		{
			$session =& JFactory::getSession();
			$session->set('username', $volunteername);
			$session->set('is_admin', $userobj->is_admin);
			
			// $this->setRedirect(JRoute::_('index.php?option=com_volunteer'));
			// return false;
			
			if ($userobj->is_admin == 'y') //if is admin
				$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=searchfile'));
			else //if is volunteer
				$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=searchfile'));
		}
		
	}
	
	
	
	function logout()
	{
		$session =& JFactory::getSession();
		$session->clear('username');
		$session->clear('is_admin');
		$this->setRedirect(JRoute::_('index.php?option=com_normal'));
	}
	
	
	function updatePassword()
	{
		if ($this->authenticate() == false)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_normal&view=login'), 'Please login to access this page','error');
			return false;
		}
		
		$session =& JFactory::getSession();
		$username = $session->get('username');
		
		$oldpassword  = JRequest::getVar('oldPassword');
		$newpassword  = JRequest::getVar('newPassword');
		$newpassword2 = JRequest::getVar('newPassword2');
		if (empty($oldpassword) || empty($newpassword) || empty($newpassword2))
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=updatepassword'), JText::sprintf(' Please fill all the details in the form '),'error');
			return false;
		}
		
		$model = $this->getModel('volunteer');
		if ($model->matchPassword($username, $oldpassword) == false)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=updatepassword'), JText::sprintf('Your current password is incorrent. Please try again.'),'error');
			return false;
		}
		
		if ($oldpasword != $newpassword)
		{
			if ($newpassword != $newpassword2)
			{
				$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=updatepassword'), JText::sprintf(' New password does not match'),'error');
				return false;
			}
			else
			{
				echo 'New password is ok '; //TODO
			}
		}
		else
		{
			echo 'Old password and new password are the same , please enter different password'; //TODO
		}
		
		// $model = $this->getModel('volunteer');
		$updatepassword = $model->updatePassword($username, $newpassword);
		
		if ($updatepassword == false)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=updatepassword'), $this->errorMessageModelError, 'error');
			return false;
		}
		else
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=volunteer'), JText::sprintf(' Password updated successfully'));
			return false;
		}
		
	}
	
	function searchfile()
	{	
		$location = JRequest::getVar('location');
		$timespan = JRequest::getVar('timespan');
		$industry = JRequest::getVar('industry');
		$keywords = JRequest::getVar('keywords');
		
		$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=searchfile&location=' . $location . '&timespan=' . $timespan . '&industry=' . $industry . '&keywords=' . $keywords . "#content"));
		// $this->setRedirect(JRoute::_('index.php'));
		return false;
	}
	
	function downloadfile()
	{
		$id       = JRequest::getVar('fileId');
		$model    = $this->getModel('volunteer');
		$download = $model->getFile($id);
		if ($download == false)
		{
			$this->setRedirect(JRoute::_('index.php'));
		}
		else
		{
			//copied and modified from http://www.finalwebsites.com/forums/topic/php-file-download
			$path     = dirname(__FILE__) . "/Audio/"; // change the path to fit your websites document structure
			$fullPath = $path . $download->url; //$path.$_POST['download_file'];
			
			if ($fd = fopen($fullPath, "r"))
			{
				$fsize      = filesize($fullPath);
				$path_parts = pathinfo($fullPath);
				$ext        = strtolower($path_parts["extension"]);
				switch ($ext)
				{
					case "mp3":
						header("Content-type: application/mp3"); // add here more headers for diff. extensions
						header("Content-Disposition: attachment; filename=\"" . $path_parts["basename"] . "\""); // use 'attachment' to force a download
						break;
					default;
						header("Content-type: application/octet-stream");
						header("Content-Disposition: filename=\"" . $path_parts["basename"] . "\"");
				}
				header("Content-length: $fsize");
				header("Cache-control: private"); //use this to open files directly
				while (!feof($fd))
				{
					$buffer = fread($fd, 2048);
					echo $buffer;
				}
			}
			fclose($fd);
			exit;
			
		}
	}
	
	
	function addfeedback()
	{
		$name = JRequest::getVar('name');
		$feed = JRequest::getVar('feedback');
		$id   = JRequest::getVar('fileId');
		
		$app = JFactory::getApplication();
		$data = array();
		$data['name'] = $name;
		$data['feedback'] = $feed;
		$data['fileId'] = $id;
		$app->setUserState('volunteer.filedetail.form.data', $data);
		
		$redirectUrl = JRoute::_('index.php?option=com_normal&view=feedback&fileId=' . $id);
		
		if (empty($name) || empty($feed))
		{
			$this->setRedirect($redirectUrl, 'Please enter Name and Feedback.', 'error');
			return false;
		}
		$model       = $this->getModel('volunteer');
		$addfeedback = $model->addFeedback($id, $name, $feed);
		
		if ($addfeedback == false)
		{
			$this->setRedirect($redirectUrl, $this->errorMessageModelError, 'error');
		}
		else
		{
		
			$app->setUserState('volunteer.filedetail.form.data', array());
			$this->setRedirect($redirectUrl, ' Thank you for your feedback.');
		}
		
	}
	
	
	function deletefeedback()
	{
		if ($this->isAdmin() == false)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_normal&view=login'), $this->errorMessageAdminPermissionRequired, 'error');
			return false;
		}
	
		$id             = JRequest::getVar('feedback');
		$model          = $this->getModel('volunteer');
		$deletefeedback = $model->deleteFeedback($id);
		if ($deletefeedback == false)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=feedback'), $this->errorMessageModelError, 'error');
			return false;
		}
		
		else
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=feedback'), JText::sprintf('Feedback deleted.'));
			return false;
		}
		
	}
	///////////////////////////////////////////////////////////////// volunteer //////////////////////////////////////////////////////////////////////////////////////////////////////////////////	
	function addvolunteer()
	{
		if ($this->isAdmin() == false)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_normal&view=login'), $this->errorMessageAdminPermissionRequired, 'error');
			return false;
		}
		
		$username   = JRequest::getVar('username');
		$pwd1       = JRequest::getVar('password');
		$repassword = JRequest::getVar('password2');
		
				$app = JFactory::getApplication();
		$data = $app->getUserState('volunteer.addfile.form.data');
		if(!$data) $data = array();
		$data['name'] = $name;
		$data['description'] = $description;
		$data['location'] = $locationId;
		$data['timespan'] = $timespanId;
		$data['industry'] = $industryId;
		$data['keywords'] = $keywordList;
		$data['acknowledgement'] = $acknowledment;
		$app->setUserState('volunteer.addfile.form.data', $data);
		
		$app = JFactory::getApplication();
		$data = array();
		$data['username'] = $username;
		$app->setUserState('volunteer.addvolunteer.form.data', $data);
		
		if (empty($username) || empty($pwd1) || empty($repassword))
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=addvolunteer'), JText::sprintf('Please enter Name and Password'),'error');
			return false;
		}
		$model           = $this->getModel('volunteer');
		$exist_volunteer = $model->existVolunteer($username);
		if ($existVolunteer == true)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=addvolunteer'), JText::sprintf('Username already exists. Please select another name', 'error'));
			return false;
		}
		if ($pwd1 != $repassword)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=addvolunteer'), JText::sprintf('Re-entered Password does not match.'), 'error');
			return false;
		}
		
		$volunteeradded = $model->addVolunteer($username, $pwd1);
		if ($volunteeradded == false)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=addvolunteer'), $this->errorMessageModelError, 'error');
			return false;
		}
		else
		{
			$app->setUserState('volunteer.addvolunteer.form.data', array());
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=searchvolunteer'), JText::sprintf('New volunteer added.'));
			return false;
		}
	}
	
	
	function searchvolunteer()
	{
	
		if ($this->isAdmin() == false)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_normal&view=login'), $this->errorMessageAdminPermissionRequired, 'error');
			return false;
		}
	
		$name = JRequest::getVar('searchname');
		// $model= $this->getModel('volunteer');
		$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=searchvolunteer&searchname=' . $name));
		return false;
	}
	
	function updatevolunteer()
	{
		if ($this->isAdmin() == false)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_normal&view=login'), $this->errorMessageAdminPermissionRequired, 'error');
			return false;
		}
		
		$username    = JRequest::getVar('username');
		$password        = JRequest::getVar('password');
		$password2 = JRequest::getVar('password2'); //re-entered password
		
		$linkFail = JRoute::_('index.php?option=com_volunteer&view=editvolunteer&volunteer=' . $username);
		
		if (empty($username) || empty($password) || empty($password2))
		{
			$this->setRedirect($linkFail, 'Please enter password.' ,'error');
			return false;
		}
		$model           = $this->getModel('volunteer');
		
		if ($password != $password2)
		{
			$this->setRedirect($linkFail, 'Re-entered password does not match.', 'error');
			return false;
		}
		
		$volunteerupdated = $model->updateVolunteer($username, $username, $password);
		if ($volunteerupdated == false)
		{
			$this->setRedirect($linkFail, $this->errorMessageModelError, 'error');
			return false;
		}
		else
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=searchvolunteer'), JText::sprintf('Volunteer updated.'));
			return false;
		}
	}
	
	
	function deletevolunteer()
	{
	
		if ($this->isAdmin() == false)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_normal&view=login'), $this->errorMessageAdminPermissionRequired, 'error');
			return false;
		}
		
		$volunteer        = JRequest::getVar('volunteer');
		$model            = $this->getModel('volunteer');
		$volunteerdeleted = $model->deleteVolunteer($volunteer);
		if ($volunteerdeleted == false)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=searchvolunteer'),$this->errorMessageModelError, 'error');
			return false;
		}
		else
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=searchvolunteer'), JText::sprintf('Volunteer Deleted successfully'));
		}
	}
	///////////////////////////////////////////////////////////////////////  Add file /////////////////////////////////////////////////////////////////////////////////////////////////////////
	
	function addfile()
	{
	
		if ($this->authenticate() == false)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_normal&view=login'), 'Please Login to view this section');
			return false;
		}
		//validate inputs 
		//if fail set error messages then redirect back to form
		
		$name          = JRequest::getVar('name');
		$description   = JRequest::getVar('description');
		$locationId    = JRequest::getVar('location');
		$timespanId    = JRequest::getVar('timespan');
		$industryId    = JRequest::getVar('industry');
		$keywordList   = JRequest::getVar('keywords');
		$acknowledment = JRequest::getVar('acknowledgement');
		$file_size     = $_FILES["file"]["size"];
		$file          = JRequest::getVar('file', null, 'FILES', 'array'); // jimport('joomla.filesystem.file');
		
		$session =& JFactory::getSession();
		$last_modified_by = $session->get('username');
		
		$app = JFactory::getApplication();
		// $data = $app->getUserState('volunteer.addfile.form.data');
		$data = array();
		$data['name'] = $name;
		$data['description'] = $description;
		$data['location'] = $locationId;
		$data['timespan'] = $timespanId;
		$data['industry'] = $industryId;
		$data['keywords'] = $keywordList;
		$data['acknowledgement'] = $acknowledment;
		$app->setUserState('volunteer.addfile.form.data', $data);
		
		
		if (empty($name) || empty($description) || empty($locationId) || empty($timespanId) || empty($industryId) || empty($acknowledment))
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=addfile'), JText::sprintf('Please enter Name, Description and Acknowledgement.'),'error');
			return false; //11
		}
		// if (file_exists($name))
		// {
			// $this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=addfile'), JText::sprintf('File name already exist'),'error');
			// return false;
		// }
		if (!is_numeric($locationId))
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=addfile'), JText::sprintf('Please select Location.'),'error');
			return false;
		}
		$linkFail = JRoute::_('index.php?option=com_volunteer&view=addfile');
		//?heck that we have a file
		if ((!empty($_FILES["file"])) && ($_FILES['file']['error'] == 0))
		{
			//Check file extension and size
			$filename = uniqid() . '_' . JFile::makeSafe(basename($_FILES['file']['name']));
			// $filename = basename($_FILES['file']['name']);
			
			$ext = substr($filename, strrpos($filename, '.') + 1);
			// echo $ext;
			
			// echo 'ext:' . $ext;
			// echo 'type:' . 			$_FILES["file"]["type"];
			// echo 'size' . $_FILES["file"]["size"];
			
			if (($ext == "mp3") && ($_FILES["file"]["type"] == "audio/mpeg" OR true) && ($_FILES["file"]["size"] < 71680000))
			{
				//if(true){
				//Determine the path to which we want to save this file
				$newname = dirname(__FILE__) . '\\Audio\\' . $filename;
				
				//Check if the file with the same name is already exists on the server
				if (!file_exists($newname))
				{
					//Attempt to move the uploaded file to it's new place
					if ((JFile::upload($_FILES['file']['tmp_name'], $newname)))
					{
						//if ((move_uploaded_file($_FILES['file']['tmp_name'],$newname))) {
						echo "It's done! The file has been saved as: " . $newname;
						// return false;
						
					}
					else
					{
							$this->setRedirect($linkFail, 'Your file could not be uploaded. Please try again.', 'error');
							return false;
					}
				}
				else
				{
					$this->setRedirect($linkFail, 'A file named ' . $filename . ' already exists in the database. Please rename your file or select another file.', 'error');
						return false;
				}
			}
			else
			{
					// echo $fileext . $_FILES["file"]["type"] . $_FILES["file"]["size"];
					$this->setRedirect($linkFail, 'Only MP3 files less than 15MB can be uploaded.', 'error');
					return false;
			}
		}
		else
		{
			$this->setRedirect($linkFail, 'Please select a file to upload.', 'error');
			return false;
		}
		
		// $filename = basename($_FILES['file']['name']);
		
		$model     = $this->getModel('volunteer');
		$fileadded = $model->addFile($name, $description, $locationId, $timespanId, $industryId, $keywordList, $filename, $acknowledment, $file_size, $last_modified_by);
		
		if ($fileadded == false)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=addfile'), $this->errorMessageModelError, 'error');
			return false;
		}
		else
		{
			$app->setUserState('volunteer.addfile.form.data', array());
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=searchfile'), JText::sprintf('File added successfully.'));
			return false;
		}
	}
	
	function updatefile()
	{
		//authenticate 
		//if fail redirect to login page
		if ($this->authenticate() == false)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_normal&view=login'), 'Please Login to view this section');
			return false;
		}
		
		$model =& $this->getModel('volunteer');
		$audiofile = $model->getFile(JRequest::getVar('fileid'));
		
		if(!$audiofile) //file does not exist in db
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=searchfile'), 'File does not exist or has been deleted', 'error');
			return false;
		}
		
		// $session =& ;
		
		$keywordList   = JRequest::getVar('keywords');
		$newmp3 = JRequest::getVar('newmp3');
		// $newmp3 = ($newmp3 == true || $newmp3 == 'true');		
		// echo $newmp3 == false; return false;
		
		// $audiofile->id = $fileId;
 		$audiofile->name = JRequest::getVar('name');		
		$audiofile->location_id = JRequest::getVar('location');
		$audiofile->timespan_id = JRequest::getVar('timespan');
		$audiofile->industry_id = JRequest::getVar('industry');
		$audiofile->description = JRequest::getVar('description');
		$audiofile->acknowledgement = JRequest::getVar('acknowledgement');
		$audiofile->file_size = $_FILES["file"]["size"];
		$audiofile->last_modified_by = JFactory::getSession()->get('username');
		$audiofile->last_modified_on = date("y.m.d");//-current date
		
		$app = JFactory::getApplication();
		$data = $app->getUserState('volunteer.editfile.form.data');
		if(!$data) $data = array();
		$data['audiofile'] = $audiofile;
		$data['keywords'] = $keywordList;
		$data['newmp3'] = $newmp3;
		$app->setUserState('volunteer.editfile.form.data', $data);

		$linkFail = JRoute::_('index.php?option=com_volunteer&view=editfile&fileid=' . $audiofile->id);		
		
		if (empty($audiofile->name) || empty($audiofile->description) || empty($audiofile->acknowledgement))
		{
			$this->setRedirect($linkFail, 'File\'s Name, Description and Acknowledgment are required.', 'error');
			return false;
		}
		
		if($newmp3 == 'new')
		{
			// echo 'newmp3' . $newmp3; return false;
			if ((!empty($_FILES["file"])) && ($_FILES['file']['error'] == 0))
			{
				//Check file extension and size
				$filename = uniqid() . '_' . JFile::makeSafe(basename($_FILES['file']['name']));
				
				$fileext = substr($filename, strrpos($filename, '.') + 1);				
				
				if (($fileext == "mp3") && ($_FILES["file"]["type"] == "audio/mpeg" OR true) && ($_FILES["file"]["size"] < 71680000))
				{
					$newname = dirname(__FILE__) . '\\Audio\\' . $filename;
					
					//Check if the file with the same name is already exists on the server
					if (!file_exists($newname))
					{
						//Attempt to move the uploaded file to it's new place
						if ((JFile::upload($_FILES['file']['tmp_name'], $newname)))
						{
							unlink(dirname(__FILE__) . '\\Audio\\' . $audiofile->url); //delete old file
							$audiofile->url = $filename; //set new filename
							
						}
						else
						{
							$this->setRedirect($linkFail, 'Your file could not be uploaded. Please try again.', 'error');
							return false;
						}
					}
					else
					{
						$this->setRedirect($linkFail, 'A file named ' . $filename . ' already exists in the system. Please rename your file or select another file.', 'error');
						return false;
					}
				}
				else
				{
					// echo $fileext . $_FILES["file"]["type"] . $_FILES["file"]["size"];
					$this->setRedirect($linkFail, 'Only MP3 files less than 15MB can be uploaded.', 'error');
					return false;
				}
			}
			else
			{
				$this->setRedirect($linkFail, 'Please select a file to upload.', 'error');
				return false;
			}
		}
		
		$result = $model->updateFile($audiofile, $keywordList);
		
		if ($result == false)
		{
			// $this->setRedirect($linkFail, $this->errorMessageModelError, 'error');
			return false;
		}
		else
		{
			$app->setUserstate('volunteer.editfile.form.data', array());
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=searchfile'), JText::sprintf('File updated successfully.'));
			return false;
		}
	}
	
	function deleteFile()
	{
		//authenticate, if fail redirect to login page
		if ($this->authenticate() == false)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_normal&view=login'), 'please Login to view this section');
			return false;
		}
		
		$fileId = JRequest::getVar('fileid');
		
		$model       = $this->getModel('volunteer');
		$filedeleted = $model->deleteFile($fileId);
		
		if ($fileadded == false)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=searchfile'), $this->errorMessageModelError, 'error');
			return false;
		}
		else
		{
			//TODO: delete mp3 file
			//if success set successful messages then redirect to view all files page			
			//index.php?option=com_volunteer&view=searchfile
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=searchfile'), JText::sprintf('File deleted successfully.'));
			return false;
		}
	}
	
	//////////////////////////////////////////////////////  Key word /////////////////////////////////////////////////////////////////////////////////////
	function addkeyword()
	{
		if ($this->isAdmin() == false)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_normal&view=login'), $this->errorMessageAdminPermissionRequired, 'error');
			return false;
		}
		
		$keywordList = JRequest::getVar('newkeyword');
		
		$app = JFactory::getApplication();
		$data = $app->getUserState('volunteer.addkeyword.form.data');
		if(!$data) $data = array();
		$data['newkeyword'] = $keywordList;
		$app->setUserState('volunteer.addkeyword.form.data', $data);
		
		if (empty($keywordList))
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=addsearchkeyword'), JText::sprintf('Please enter Keyword here'),'error');
			return false;
		}
		$model =& $this->getModel('volunteer');
		$exist_keyword = $model->existKeyword($keywordList);
		
		if ($exist_keyword == true)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=addsearchkeyword'), JText::sprintf('Keyword already exist in the database'),'error');
			return false;
		}
		
		//$model =  $this->getModel('volunteer');
		$keywordadded = $model->addKeyword($keywordList);
		
		
		if ($keywordadded == false)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=addsearchkeyword'), $this->errorMessageModelError, 'error');
			return false;
		}
		else
		{
			$app->setUserstate('volunteer.addkeyword.form.data', array());
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=addsearchkeyword'), JText::sprintf('Keyword is added to the Keyword List.'));
			return false;
		}
	}
	
	
	
	function searchkeyword()
	{
	
		if ($this->isAdmin() == false)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_normal&view=login'), $this->errorMessageAdminPermissionRequired, 'error');
			return false;
		}
		$keyword = JRequest::getVar('searchkeyword');
		
		$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=addsearchkeyword&searchkeyword=' . $keyword));
		return false;
	}
	
	
	function updatekeyword()
	{
	
		if ($this->isAdmin() == false)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_normal&view=login'), $this->errorMessageAdminPermissionRequired, 'error');
			return false;
		}
		
		
		$oldkeyword = JRequest::getVar('oldkeyword');
		$newkeyword = JRequest::getVar('newkeyword');
		
		
		$app = JFactory::getApplication();
		$data = $app->getUserState('volunteer.editkeyword.form.data');
		if(!$data) $data = array();
		$data['newkeyword'] = $newkeyword;
		$app->setUserState('volunteer.editkeyword.form.data', $data);
		
		
		
		if (empty($newkeyword))
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=editkeyword'), JText::sprintf('Please enter Keyword here'), 'error');
			// echo 'nothing';
			return false;
		}
		$model         = $this->getModel('volunteer');
		$exist_keyword = $model->existKeyword($newkeyword);
		
		if ($exist_keyword == true)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=editkeyword'), JText::sprintf('Keyword already exist in the database'),'error');
			return false;
		}
		
		// $model =  $this->getModel('volunteer');
		$keywordupdated = $model->updateKeyword($oldkeyword, $newkeyword);
		
		
		if ($keywordupdated == false)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=editkeyword'), $this->errorMessageModelError, 'error');
			return false;
		}
		else
		{
			$app->setUserstate('volunteer.editkeyword.form.data', array());
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=addsearchkeyword'), JText::sprintf('Keyword is updated.'));
			return false;
		}
		
		
	}
	
	function deletekeyword()
	{
	
		if ($this->isAdmin() == false)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_normal&view=login'), $this->errorMessageAdminPermissionRequired, 'error');
			return false;
		}
		
		
		$keyword        = JRequest::getVar('keyword');
		$model          = $this->getModel('volunteer');
		$keyworddeleted = $model->deleteKeyword($keyword);
		
		if ($keyworddeleted == false)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=addsearchkeyword'), $this->errorMessageModelError, 'error');
			return false;
		}
		else
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=addsearchkeyword'), JText::sprintf('Keyword is deleted from the Keyword List.'));
			return false;
		}
	}
	
	
	///////////////////////////////////////////////////   Locations /////////////////////////////////////////////////////////////////////////////////////////////////////////
	function addlocation()
	{
	
		if ($this->isAdmin() == false)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_normal&view=login'), $this->errorMessageAdminPermissionRequired, 'error');
			return false;
		}
		
		
		$location = JRequest::getVar('newlocation');
		
		$app = JFactory::getApplication();
		$data = $app->getUserState('volunteer.addsearchlocation.form.data');
		if(!$data) $data = array();
		$data['newlocation'] = $location;
		$app->setUserState('volunteer.addsearchlocation.form.data', $data);
		
		if (empty($location))
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=addsearchlocation'), JText::sprintf('Please enter Location here'),'error');
			return false;
		}
		$model =& $this->getModel('volunteer');
		$exist_location = $model->existLocation($location);
		
		if ($exist_location)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=addsearchlocation'), JText::sprintf('Duplicated name. Please enter another name.'),'error');
			return false;
		}
		
		$add_location = $model->addLocation($location);
		
		if ($add_location == false)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=addsearchlocation'), $this->errorMessageModelError, 'error');
			return false;
		}
		
		else
		{
			$app->setUserstate('volunteer.addsearchlocation.form.data', array());
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=addsearchlocation'), JText::sprintf('location is added to the location List.'));
			return false;
		}
	}
	function searchlocation()
	{
	
		if ($this->isAdmin() == false)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_normal&view=login'), $this->errorMessageAdminPermissionRequired, 'error');
			return false;
		}
		
		
		$location = JRequest::getVar('searchlocation');
		
		$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=addsearchlocation&searchlocation=' . $location));
		return false;
	}
	
	function updatelocation()
	{
	
		if ($this->isAdmin() == false)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_normal&view=login'), $this->errorMessageAdminPermissionRequired, 'error');
			return false;
		}
		
		
		$oldLocation = JRequest::getVar('oldlocation');
		$newlocation = JRequest::getVar('newlocation');
		
		$app = JFactory::getApplication();
		$data = $app->getUserState('volunteer.editlocation.form.data');
		if(!$data) $data = array();
		$data['newlocation'] = $newlocation;
		$app->setUserState('volunteer.editlocation.form.data', $data);
		
		if (empty($newlocation))
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=editlocation&location=' . $oldLocation), JText::sprintf('Please enter location here'),'error');
			return false;
		}
		$model          = $this->getModel('volunteer');
		$exist_location = $model->existLocation($newlocation);
		
		if ($exist_location == true)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=editlocation&location=' . $oldLocation), JText::sprintf('location already exist in the database'),'error');
			return false;
		}
		
		
		$locationUpdated = $model->updateLocation($oldLocation, $newlocation);
		
		
		if ($locationUpdated = false)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=editlocation&location=' . $oldLocation), $this->errorMessageModelError, 'error');
			return false;
		}
		else
		{
			$app->setUserstate('volunteer.editlocation.form.data', array());
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=addsearchlocation'), JText::sprintf('Location is updated.'));
			return false;
			
		}
	}
	
	function deletelocation()
	{
	
		if ($this->isAdmin() == false)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_normal&view=login'), $this->errorMessageAdminPermissionRequired, 'error');
			return false;
		}
		
		
		$location_id = JRequest::getVar('location');
		
		$model           = $this->getModel('volunteer');
		$locationdeleted = $model->deleteLocation($location_id);
		if ($locationdeleted == false)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=addsearchlocation'), $this->errorMessageModelError, 'error');
			return false;
		}
		else
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=addsearchlocation'), JText::sprintf('Location deleted successfully'));
			return false;
		}
	}
	
	
	////////////////////////////////////////////////////////////// TIME SPAN ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	
	function addtimespan()
	{
	
		if ($this->isAdmin() == false)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_normal&view=login'), $this->errorMessageAdminPermissionRequired, 'error');
			return false;
		}
		
		
		$timespan = JRequest::getVar('newtimespan');
		
		$app = JFactory::getApplication();
		$data = $app->getUserState('volunteer.addsearchtimespan.form.data');
		if(!$data) $data = array();
		$data['newtimespan'] = $timespan;
		$app->setUserState('volunteer.addsearchtimespan.form.data', $data);
		
		if (empty($timespan))
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=addsearchtimespan'), JText::sprintf('Please enter timespan here'),'error');
			return false;
		}
		$model          = $this->getModel('volunteer');
		$exist_timespan = $model->existTimespan($timespan);
		
		if ($exist_timespan == true)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=addsearchtimespan'), JText::sprintf('Timespan already exist in the database'),'error');
			return false;
		}
		
		$model         = $this->getModel('volunteer');
		$timespanadded = $model->addTimespan($timespan);
		
		
		if ($timespanadded = false)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=addsearchtimespan'), $this->errorMessageModelError, 'error');
			return false;
		}
		else
		{
			$app->setUserstate('volunteer.addsearchtimespan.form.data', array());
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=addsearchtimespan'), JText::sprintf('Timespan is added to the List.'));
			return false;
		}
	}
	
	function searchtimespan()
	{
	
		if ($this->isAdmin() == false)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_normal&view=login'), $this->errorMessageAdminPermissionRequired, 'error');
			return false;
		}
		
		$span = JRequest::getVar('searchtimespan');
		
		$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=addsearchtimespan&searchtimespan=' . $span));
		return false;
	}
	
	
	
	function updatetimespan()
	{
	
		if ($this->isAdmin() == false)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_normal&view=login'), $this->errorMessageAdminPermissionRequired, 'error');
			return false;
		}
	
		$oldtimespan = JRequest::getVar('oldtimespan');
		
		$newtimespan = JRequest::getVar('newtimespan');
		
		$app = JFactory::getApplication();
		$data = $app->getUserState('volunteer.edittimespan.form.data');
		if(!$data) $data = array();
		$data['newtimespan'] = $newtimespan;
		$app->setUserState('volunteer.edittimespan.form.data', $data);
		
		if (empty($newtimespan))
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=edittimespan&timespan=' . $oldtimespan), JText::sprintf('Please enter timespan here'),'error');
			return false;
		}
		$model          = $this->getModel('volunteer');
		$exist_timespan = $model->existTimespan($newtimespan);
		
		if ($exist_timespan == true)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=edittimespan&timespan=' . $oldtimespan), JText::sprintf('Timespan already exist in the database'),'error');
			return false;
		}
		
		// $model =  $this->getModel('volunteer');
		$timespanupdated = $model->updateTimespan($oldtimespan, $newtimespan);
		
		
		if ($timespanupdated = false)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=edittimespan&timespan=' . $oldtimespan), $this->errorMessageModelError, 'error');
			return false;
		}
		else
		{
			$app->setUserstate('volunteer.edittimespan.form.data', array());
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=addsearchtimespan'), JText::sprintf('Timespan is updated.'));
			return false;
			
		}
	}
	
	function deletetimespan()
	{
	
		if ($this->isAdmin() == false)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_normal&view=login'), $this->errorMessageAdminPermissionRequired, 'error');
			return false;
		}	
	
		$timespan = JRequest::getVar('timespan');
		
		$model           = $this->getModel('volunteer');
		$timespandeleted = $model->deleteTimespan($timespan);
		
		if ($timespandeleted == false)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=addsearchtimespan'), $this->errorMessageModelError, 'error');
			return false;
		}
		else
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=addsearchtimespan'), JText::sprintf('Timespan deleted successfully'));
			return false;
		}
	}
	
	
	
	////////////////////////////////////////////////////////////////////////////  Industry  //////////////////////////////////////////////////////////////////////////////////////////
	
	function addindustry()
	{
	
		if ($this->isAdmin() == false)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_normal&view=login'), $this->errorMessageAdminPermissionRequired, 'error');
			return false;
		}
		
		
		$Industry = JRequest::getVar('newindustry');
		
		$app = JFactory::getApplication();
		$data = $app->getUserState('volunteer.addsearchindustry.form.data');
		if(!$data) $data = array();
		$data['newindustry'] = $Industry;
		$app->setUserState('volunteer.addsearchindustry.form.data', $data);
		
		if (empty($Industry))
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=addsearchindustry'), JText::sprintf('Please enter Industry here'),'error');
			return false;
		}
		$model          = $this->getModel('volunteer');
		$exist_industry = $model->existIndustry($Industry);
		
		if ($exist_industry == true)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=addsearchindustry'), JText::sprintf('Industry already exist in the database'),'error');
			return false;
		}
		
		$model         = $this->getModel('volunteer');
		$industryadded = $model->addIndustry($Industry);
		
		
		if ($industryadded = false)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=addsearchindustry'), $this->errorMessageModelError, 'error');
			return false;
		}
		else
		{
			$app->setUserstate('volunteer.addsearchindustry.form.data', array());
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=addsearchindustry'), JText::sprintf('Industry is added to the List.'));
			return false;
		}
		
	}
	
	
	function searchindustry()
	{
	
		if ($this->isAdmin() == false)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_normal&view=login'), $this->errorMessageAdminPermissionRequired, 'error');
			return false;
		}
	
		$industry = JRequest::getVar('searchindustry');
		
		$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=addsearchindustry&searchindustry=' . $industry));
		return false;
	}
	
	function updateindustry()
	{
	
	
		if ($this->isAdmin() == false)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_normal&view=login'), $this->errorMessageAdminPermissionRequired, 'error');
			return false;
		}
		
		
		$oldindustry = JRequest::getVar('oldindustry');
		
		$newindustry = JRequest::getVar('newindustry');
		
		$app = JFactory::getApplication();
		$data = $app->getUserState('volunteer.editindustry.form.data');
		if(!$data) $data = array();
		$data['newindustry'] = $newindustry;
		$app->setUserState('volunteer.editindustry.form.data', $data);
		
		if (empty($newindustry))
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=editindustry&industry=' . $oldindustry), JText::sprintf('Please enter new Industry here'),'error');
			return false;
		}
		$model          = $this->getModel('volunteer');
		$exist_industry = $model->existIndustry($newindustry);
		
		if ($exist_industry == true)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=editindustry&industry=' . $oldindustry), JText::sprintf('Industry already exist in the database'),'error');
			return false;
		}
		
		// $model =  $this->getModel('volunteer');
		$industryupdated = $model->updateIndustry($oldindustry, $newindustry);
		
		
		if ($industryupdated = false)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=editindustry&industry=' . $oldindustry), $this->errorMessageModelError, 'error');
			return false;
		}
		else
		{
			$app->setUserstate('volunteer.editindustry.form.data', array());
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=addsearchindustry'), JText::sprintf('Industry is updated.'));
			return false;
			
		}
	}
	
	
	function deleteindustry()
	{
	
		if ($this->isAdmin() == false)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_normal&view=login'), $this->errorMessageAdminPermissionRequired, 'error');
			return false;
		}
		
		
		$industry        = JRequest::getVar('industry');
		$model           = $this->getModel('volunteer');
		$industrydeleted = $model->deleteIndustry($industry);
		if ($industry == false)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=addsearchindustry'), $this->errorMessageModelError, 'error');
		}
		else
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=addsearchindustry'), JText::sprintf('Industry is deleted.'));
			return false;
			
		}
		
	}
	
	
	
	//////////////////////////////////////////////////////////// Sponser links //////////////////////////////////////////////////////////////////////////////////////////////////
	
	function addlink()
	{
		if ($this->isAdmin() == false)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_normal&view=login'), $this->errorMessageAdminPermissionRequired, 'error');
			return false;
		}
	
		$newlinkname = JRequest::getVar('newlinkname');
		$newlinkurl  = JRequest::getVar('newlinkurl');
		

		$app = JFactory::getApplication();
		// $data = $app->getUserState('volunteer.addsearchlink.form.data');
		$data = array();
		$data['newlinkname'] = $newlinkname;
		$data['newlinkurl'] = $newlinkurl;
		$app->setUserState('volunteer.addsearchlink.form.data', $data);
		
		if (empty($newlinkname) || empty($newlinkurl))
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=addsearchlink'), JText::sprintf('Please enter Name and URL.'), 'error');
			return false;
		}
		$model     = $this->getModel('volunteer');
		// IGNORE DUPLICATED LINK FOR NOW - Mike 03/05/2011
		// $exit_link = $model->existLink($linkurl);
		// if ($exit_link == true)
		// {
			// $this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=addsearchlink'), JText::sprintf('Link Url already exist, please choose another one'));
			// return false;
		// }
		
		$addlink = $model->addLink($newlinkurl, $newlinkname);
		
		if ($addlink == false)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=addsearchlink'), JText::sprintf('There has been error with the system. Please try again.'), 'error');
			return false;
		}
		else
		{
			$app->setUserState('volunteer.addsearchlink.form.data', array());
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=addsearchlink'), JText::sprintf('Sponsor link added.'));
			return false;
		}
		
		
	}
	
	
	function searchlink()
	{
		if ($this->isAdmin() == false)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_normal&view=login'), $this->errorMessageAdminPermissionRequired, 'error');
			return false;
		}
		
		$searchlink = JRequest::getVar('searchlink');
		
		$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=addsearchlink&searchlink=' . $searchlink));
		return false;
	}
	
	
	function updatelink()
	{
		if ($this->isAdmin() == false)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_normal&view=login'), $this->errorMessageAdminPermissionRequired, 'error');
			return false;
		}
		
		$linkname = JRequest::getVar('name');
		// $linkname2 = JRequest::getVar('name2');
		$linkId   = JRequest::getVar('id');
		$linkurl  = JRequest::getVar('url');
		// $linkurl2 = JRequest::getVar('url2');
		
		$app = JFactory::getApplication();
		// $data = $app->getUserState('volunteer.editlink.form.data');
		$data = array();
		$data['id'] = $linkId;
		$data['name'] = $linkname;
		$data['url'] = $linkurl;
		$app->setUserState('volunteer.editlink.form.data', $data);		
		
		if (empty($linkname) || empty($linkurl))
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=editlink&link=' . $linkId), JText::sprintf('Please enter Name and URL.'), 'error');
			return false;
		}
		
		$model     = $this->getModel('volunteer');
		// IGNORE DUPLICATED LINK FOR NOW - Mike 03/05/2011
		// $exit_link = $model->existLink($linkurl);
		// if ($exit_link == true)
		// {
			// $this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=editlink&link=' . $linkId), JText::sprintf('Link Url already exist, please choose another one'));
			// return false;
		// }
		
		$updatelink = $model->updateLink($linkId, $linkurl, $linkname);
		
		if ($updatelink == false)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=editlink&link=' . $linkId), $this->errorMessageModelError, 'error');
			return false;
		}
		else
		{
			$app->setUserstate('volunteer.editlink.form.data', array());
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=addsearchlink'), JText::sprintf('Sponsor link updated.'));
			return false;
		}
		
	}
	
	
	function deletelink()
	{
		if ($this->isAdmin() == false)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_normal&view=login'), $this->errorMessageAdminPermissionRequired, 'error');
			return false;
		}
		
		$linkId     = JRequest::getVar('link');
		$model      = $this->getModel('volunteer');
		$deletelink = $model->deleteLink($linkId);
		if ($deletelink == false)
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=addsearchlink'), $this->errorMessageModelError, 'error');
			return false;
		}
		else
		{
			$this->setRedirect(JRoute::_('index.php?option=com_volunteer&view=addsearchlink'), JText::sprintf('LinkUrl successfully deleted'));
			return false;
		}
	}
}
?>
